package com.coco.action;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.coco.utils.CommonsUtils;
import com.coco.utils.MD5Utils;
import com.coco.utils.SendJMail;
import com.coco.base.BaseServlet;
import com.coco.model.User;
/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    
	protected void login(HttpServletRequest request,HttpServletResponse response) throws SQLException, ServletException, IOException{
		String uname = request.getParameter("uname");
		String upwd = request.getParameter("upwd");
		String md5upwd = MD5Utils.md5(upwd);
		String rememberMe=request.getParameter("rememberMe");
		
		Cookie cookieusername = new Cookie("username",uname);
		Cookie cookieupwd = new Cookie("upwd",upwd);
		
		User u=userServiceImpl.login(uname,md5upwd);
		if(u!=null){
			if("0".equals(u.getState())){
				response.getWriter().write("<script type='text/javascript'>alert('账户未激活，请激活后登陆');window.location.href='"+request.getContextPath()+"/login.jsp'</script>");
				return;
			}
			if("on".equals(rememberMe)){
				cookieusername.setMaxAge(15*24*3600);
				cookieupwd.setMaxAge(15*24*3600);
			}else {
				cookieusername.setMaxAge(0);
				cookieupwd.setMaxAge(0);
			}
			response.addCookie(cookieusername);
			response.addCookie(cookieupwd);
			request.getSession().setAttribute("user", u);
			request.getRequestDispatcher("index.jsp").forward(request, response);
		} else {
			response.getWriter().write("<script type='text/javascript'>alert('密码错误');window.location.href='"+request.getContextPath()+"/login.jsp'</script>");
		}
		
		
	}
	
	/*protected void findByName(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException{
		response.setContentType("text/json;charset=utf-8");
		String uname = request.getParameter("uname");
		boolean flag=userServiceImpl.findByName(uname);
		if(flag){
			response.getWriter().write("{\"flag\":\"yes\"}");
		} else {
			response.getWriter().write("{\"flag\":\"no\"}");
		}
	}*/
	
	protected void loginOut(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException, SQLException{
		request.getSession().invalidate();
		
		//有自动登录的功能 把自动登录的cookie清除
		Cookie c = new Cookie("autologin", "");
		c.setMaxAge(0);
		response.addCookie(c);
		
		response.sendRedirect("login.jsp");
	}

	protected void register(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException, SQLException{
		Map<String,String[]> map = request.getParameterMap();
		User u = new User();
		try {
			BeanUtils.populate(u, map);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
				
		}
		
		//随机生成id和激活码code
		u.setUid(CommonsUtils.getUUID());
		u.setCode(CommonsUtils.getUUID());
		
		//MD5加密
		u.setUpwd(MD5Utils.md5(request.getParameter("upwd")));
		
		boolean flag = userServiceImpl.register(u);
		if(flag){
			//发送激活邮件
			String emailMsg = "http://10.7.181.104:8080/"+request.getContextPath()+"/userServlet?uid="+u.getUid()+"&code="+u.getCode()+"&action=activeCode";
			SendJMail.sendMail(u.getUemail(), emailMsg);
			response.sendRedirect("registersuccess.jsp");
		} else {
			request.setAttribute("registererror", "服务端异常，注册失败");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}
	}
	
	protected void activeCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException{
		String uid = request.getParameter("uid");
		String code = request.getParameter("code");
		boolean flag = userServiceImpl.active(uid,code);
		if(flag){
			boolean flag_=userServiceImpl.active1(uid);
			if(flag_){
				request.getRequestDispatcher("activesuccess.jsp").forward(request, response);
			}else {
				request.getRequestDispatcher("registersuccess.jsp").forward(request,response);
			}
		} 
	}
	
	protected void ajaxFindByName(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException{
		response.setContentType("text/json;charset=utf-8");
		String uname = request.getParameter("uname");
		boolean flag=userServiceImpl.findByName(uname);
		if(flag){
			response.getWriter().write("{\"flag\":\"1\"}");
		} else {
			response.getWriter().write("{\"flag\":\"0\"}");
		}
	}
	
	protected void codeImageCheck(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/json;charset=utf-8");
		String code=request.getParameter("code");
		String code_=(String) request.getSession().getAttribute("checkcode_session");
		if(code.equals(code_)){
			response.getWriter().write("{\"flag\":\"1\"}");
		}else{
			response.getWriter().write("{\"flag\":\"0\"}");
		}
		
	}
	
}
